package com.maven.zh.util;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class SQLUtils {

	static String url;
	static String user;
	static String password;
	static String className;
	/*
	 * 1.读取配置文件
	 * 2.注册驱动
	 */
	static{
		try {
			//读取jdbc.properties文件，得到数据库连接需要用到的字符串
			Properties properties  = new Properties();
			
			//获取编译后jdbc.properties所在的路径
			String filePath = SQLUtils.class.getClassLoader().getResource("/config/jdbc.properties").getPath(); 
			
			properties.load(new FileInputStream(filePath));
			
			 url = properties.getProperty("jdbc.url1");
			 user = properties.getProperty("jdbc.user");
			 password = properties.getProperty("jdbc.password");
			 className=properties.getProperty("jdbc.driver");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//注册驱动
		try {
			Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 获取连接
	 * @return 连接对象
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url,user,password);
	}
	
	/**
	 * 获取连接
	 * @return 连接对象
	 * @throws SQLException 
	 */
	public static Connection getConnection(String ip, String dbname, int port,
			String user, String password) throws SQLException{
		
		String url = "jdbc:mysql://"+ ip +":"+ port +"/"+ dbname 
				+"?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8";
			
		return DriverManager.getConnection(url, user, password);
	}

	/**
	 * 释放资源
	 * @param connection
	 * @param statement
	 * @param set
	 */
	public static void release(Connection connection,Statement statement,ResultSet set){
		
		if (set!=null) {
			try {
				set.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (statement!=null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (connection!=null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
}

